import random
from itertools import islice


def sample(alist, alpha):
    return random.sample(alist, int(alpha * len(alist)))


def split_by(iterable, pred):
    '''
    >>> split_by([1,2,3,4], lambda x: x%2)
    ([2, 4], [1, 3])
    '''
    d = ([], [])
    for ex in iterable:
        d[pred(ex)].append(ex)
    return d


def random_split(iterable, p=0.1, rand=random.random):
    return split_by(iterable, lambda x: p > rand())


def max_k(iterable, k, key):
    return list(islice(sorted(iterable, key=key, reverse=True), 0, k))


if __name__ == "__main__":
    import doctest
    doctest.testmod()
